package com.frame.cfg;

import java.util.Enumeration;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.mini.core.EntityInfo;
import com.mini.core.EntityMapping;
import com.mini.core.WeakEntity;
import com.mini.core.WeakEntityRowMapper;
import com.mini.core.utils.MiniUtil;

public class MiniMethodArgumentsResolver implements HandlerMethodArgumentResolver {
	private static final Logger logger = LoggerFactory.getLogger(MiniMethodArgumentsResolver.class);
	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container, NativeWebRequest webRequest,
			WebDataBinderFactory webDataBinderFactory) throws Exception {
		HttpServletRequest request = webRequest.getNativeRequest(HttpServletRequest.class);
		logger.debug("You Request Content Type is "+request.getContentType());
        // content-type不是json的不处理
        if (request.getContentType().contains("application/json")) {
            return null;
        }else{
        	String paraName = parameter.getParameterName();
        	WeakEntity weak = (WeakEntity) parameter.getParameterType().newInstance();
        	EntityInfo entityInfo = EntityMapping.me().getEntity(parameter.getParameterType());
        	Set<String> set = ((WeakEntityRowMapper)entityInfo.getRowMapper()).getMappedProperties();
        	Enumeration paramNames = request.getParameterNames(); 
        	while (paramNames.hasMoreElements()) {  
        	      String paramName = (String) paramNames.nextElement();  
        	      String[] paramValues = request.getParameterValues(paramName);  
        	      if (paramValues.length == 1) {  
        	        String paramValue = paramValues[0];  
        	        if (paramValue.length() != 0) {  
        	        	logger.debug("paramter：" + paramName + "=" + paramValue);  
        	        	if(paramName.startsWith(paraName+".")){
        	        		int start = paramName.indexOf(".");
        	        		String p = paramName.substring(start+1);
        	        		if(set.contains(p)){
        	        			weak.put(p, paramValue);
        	        		}
        	        	}else{
        	        		if(set.contains(paramName)){
        	        			weak.put(paramName, paramValue);
        	        		}
        	        	}
        	        }  
        	      }  
        	 } 
        	return weak;
        }
	}

	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return MiniUtil.isWeakEntity(parameter.getParameterType());
	}

}
